package org.atovio.problem.controller;

import org.atovio.problem.config.BookContainer;
import org.atovio.problem.exception.BookNotFoundException;
import org.atovio.problem.pojo.BookRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author AtoVio, Winter Yuan
 */
@RestController
public class BookController {

    @Autowired
    private BookContainer bookContainer;

    // 根据ISBN查询图书，如果没查到就返回异常
    @GetMapping("/books")
    public BookRecord getBookRecord(String isbn) {

        Optional<BookRecord> bookRecord = bookContainer.getBooks().stream()
                .filter(elt -> elt.isbn().equals(isbn))
                .findFirst();

        if (bookRecord.isEmpty()) {
            throw new BookNotFoundException("不存在ISBN为 [" + isbn + "] 的书籍");
        }

        return bookRecord.get();
    }
}
